package com.oop.example.work.bel;

import com.oop.example.utils.Utils;
import com.oop.example.xml.Entry;
import com.oop.example.xml.Homonym;
import java.io.ByteArrayInputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;

/**
 * Форматирует шапку
 */
public class HeaderFormatter {

    public String mainEntryHeader = "";
    public String entryHeader = "";

    public HeaderFormatter(String mainEntryHeader, String entryHeader) {
        this.entryHeader = entryHeader.trim();
        String[] split = mainEntryHeader.trim().split("\\,");
        this.mainEntryHeader = split[0].trim();

    }

    public boolean hasDotInHeader() {
        return dotInHeader;
    }

    public boolean hasTildaHeader() {
        return tildaHeader;
    }
    boolean dotInHeader = false;
    boolean tildaHeader = false;
    static String[] glasn = {"а", "е", "ё", "и", "о", "у", "ы", "э", "ю", "я", "ь", "й"};
    static String[] soglasn = {"б", "в", "г", "д", "ж", "з", "к", "л", "м", "н", "п", "р", "с", "т", "ф", "х", "ц", "ч", "ш", "щ", "ъ"};
    //static String[] homonym = {"VIII", "VII", "VI", "V", "IV", "III", "II", "I"};

    public String getFormatted() {
        String result = entryHeader;


        result = result.replaceAll("\\^\\|", "(");
        result = result.replaceAll("\\|\\^", ")");
        result = result.replaceAll("<", "");
        result = result.replaceAll(">", "");
        //System.out.println("Header:" + result);
        //System.out.println("HeaderFormatter input: entryHeader=" + entryHeader + ", mainEntryHeader=" + mainEntryHeader);
        String dotCut = mainEntryHeader.substring(0, 1);
        //System.out.println("before cut " + mainEntryHeader);
        for (String s : Utils.homonymNumeration) {
            mainEntryHeader = mainEntryHeader.replace(s, "");
        }
        //System.out.println("after cut " + mainEntryHeader);

        dotInHeader = true;
        if (entryHeader.startsWith(dotCut + ".")) {//начинается с сокращения без ударения
            result = entryHeader.replaceAll(dotCut + "\\.", mainEntryHeader);
        } else if (entryHeader.startsWith(dotCut + Utils.ACCENT_SYMBOL + ".")) {//начинается с сокращения с ударением
            result = entryHeader.replaceAll(dotCut + Utils.ACCENT_SYMBOL + "\\.", mainEntryHeader);
        } else if (entryHeader.contains(dotCut + ".")) {
            dotCut = " " + dotCut;
            result = entryHeader.replaceAll(dotCut + "\\.", " " + mainEntryHeader);
        } else if (entryHeader.contains(dotCut + Utils.ACCENT_SYMBOL + ".")) {
            dotCut = " " + dotCut;
            result = entryHeader.replaceAll(dotCut + Utils.ACCENT_SYMBOL + "\\.", " " + mainEntryHeader);
        } else {
            dotInHeader = false;
        }
        if (result.contains(".")) {
            throw new RuntimeException("Необработанная точка");
        }


        if (result.indexOf("~") >= 0) {
            tildaHeader = true;
            String sokr = getSokr(result);
            boolean glasAfterTilda = isGlasAfterTilda(sokr);
            if (glasAfterTilda) {
                result = result.replace(sokr, mergeGlasn(sokr, mainEntryHeader));
            } else {
                result = result.replace(sokr, mergeSoglasn(sokr, mainEntryHeader));
            }
        }
        return result;
    }

    public static boolean isGlasAfterTilda(String str) {
        if (str.indexOf("~") < 0) {
            throw new IllegalArgumentException("Нету тильды");
        }
        if (str.length() < 2) {
            throw new IllegalArgumentException("За тильдой нет окончания");
        }
        String firstChar = str.replace("~", "").trim().substring(0, 1);
        for (String s : glasn) {
            if (s.equalsIgnoreCase(firstChar)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Получает сокращение включая тильду из исходной строки: из строки <b>но́ги ~я́т</b> вернет <b>~я́т</b>
     * @return 
     */
    public static String getSokr(String src) {
        if (src.indexOf("~") < 0) {
            throw new IllegalArgumentException("Нету тильды");
        }
        int idexOfTilda = src.indexOf("~");
        int indexOfEnd = src.indexOf(" ", idexOfTilda + 1);
        if (indexOfEnd < 0) {
            indexOfEnd = src.length();
        }
        String result = src.substring(idexOfTilda, indexOfEnd);
        return result;
    }

    /**/
    public static String mergeGlasn(String tilda, String word) {
        if (tilda.contains(Utils.ACCENT_SYMBOL)) {
            word = word.replaceAll(Utils.ACCENT_SYMBOL, "");
        }
        int indexOfSogl = -1;
        for (String s : soglasn) {
            //System.out.print(s);
            int tempIng = word.lastIndexOf(s);
            if (tempIng > indexOfSogl) {
                indexOfSogl = tempIng;
            }
        }
        //System.out.println();
        String result = word.substring(0, indexOfSogl + 1) + tilda.replace("~", "");
        return result;
    }

    public static String mergeSoglasn(String tilda, String word) {
        if (tilda.contains(Utils.ACCENT_SYMBOL)) {
            word = word.replaceAll(Utils.ACCENT_SYMBOL, "");
        }
        int indexOfSogl = -1;
        for (String s : soglasn) {
            //System.out.print(s);
            int tempIng = word.lastIndexOf(s);
            if (tempIng > indexOfSogl) {
                indexOfSogl = tempIng;
            }
        }
        //System.out.println();
        String result = word.substring(0, indexOfSogl) + tilda.replace("~", "");
        return result;
    }

    public static void main(String[] args) throws Exception {

        JAXBContext ctx = JAXBContext.newInstance(Entry.class);
        Unmarshaller unmarshaller = ctx.createUnmarshaller();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Entry unmarshal = (Entry) unmarshaller.unmarshal(inputStream);
        System.out.println(unmarshal);
        //ObjectFactory factory = new ObjectFactory();
        for (JAXBElement<?> o : unmarshal.getContent().getClassifierOrPronunciationOrHomonym()) {
            if (o.getValue() instanceof Homonym) {
                System.out.println("Homonym!");
            }
        }
    }
    static String xml = "<entry><entryAttributes><indexInclude>true</indexInclude></entryAttributes><heading><vocable><part><simple accentSymbolNumber=\"4\">бензин</simple></part></vocable></heading><content><homonym numerator=\"I\"><variant numerator=\"1.\"><sense numerator=\"1)\"><sub-sense numerator=\"a)\"><translation><far><near><simple accentSymbolNumber=\"5\"> бензін, -ну </simple><label>м.</label></near></far></translation></sub-sense></sense></variant></homonym></content></entry>";
}
